﻿@{
    ViewData["Title"] = "库表管理";
    Layout = "~/Views/Shared/_LayoutWithTree.cshtml";
}
@section Left {
    <div class="layui-tab layui-tab-brief">
        <ul class="layui-tab-title">
            <li class="layui-this">数据库连接</li>
        </ul>
        <div class="layui-code-tools">
            <i id="btnReload" class="layui-icon layui-icon-refresh-3"></i>
        </div>
        <div class="layui-tab-content">
            <div id="toolbarDiv" style="height:calc(100vh - 90px);overflow-x:hidden; overflow-y:auto">
                <ul id="demoTree" class="dtree"></ul>
            </div>
        </div>
    </div>
}
@section Main {
    <div class="layui-tab layui-tab-brief">
        <ul class="layui-tab-title">
            <li class="layui-this"><span id="key">db</span></li>
        </ul>
        <div class="layui-code-tools">
            <button id="btnAddTable" type="button" class="layui-btn layui-btn-sm layui-hide">新建表</button>
            <button id="btnAddColumn" type="button" class="layui-btn layui-btn-sm layui-hide">添加列</button>
        </div>
        <div class="layui-tab-content layui-padding-2">
            <table class="layui-hide" id="lsttable"></table>
            <script type="text/html" id="bar">
                <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
                <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</a>
                <a class="layui-btn layui-btn-xs" lay-event="more">更多
                  <i class="layui-icon layui-icon-down"></i>
                </a>
            </script>
            <script type="text/html" id="bar_1">
                <a class="layui-btn layui-btn-xs" lay-event="edit_1">编辑</a>
                <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del_1">删除</a>
            </script>
        </div>
    </div>

    <div id="divWin" class="layui-padding-3" style="display:none">
        <form class="layui-form" action="" lay-filter="val-filter">
            <div class="layui-form-item">
                <label class="layui-form-label">名称</label>
                <div class="layui-input-block">
                    <input type="hidden" name="configId">
                    <input type="hidden" name="oldTableName">
                    <input type="text" name="tableName" lay-verify="required" placeholder="请输入表名称" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">描述</label>
                <div class="layui-input-block">
                    <input type="text" name="description" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="submit" class="layui-btn" lay-submit lay-filter="saveTable">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>

    <div id="divWin_1" class="layui-padding-3" style="display:none">
        <form class="layui-form" action="" lay-filter="val-filter_1">
            <div class="layui-form-item">
                <label class="layui-form-label">表名</label>
                <div class="layui-input-block">
                    <input type="hidden" name="configId">
                    <input type="text" name="tableName" disabled class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">实体名称</label>
                <div class="layui-input-block">
                    <input type="text" name="entityName" lay-verify="required" placeholder="请输入实体名称" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">基类</label>
                <div class="layui-input-block">
                    <select name="baseClassName">
                        <option value="EntityBase">EntityBase【基础实体】</option>
                        <option value="EntityBaseData">EntityBaseData【业务实体】</option>
                        <option value="EntityBaseId">EntityBaseId【基础实体Id】</option>
                        <option value="EntityTenant">EntityTenant【租户实体】</option>
                        <option value="EntityTenantId">EntityTenantId【租户实体Id】</option>
                        <option value="code">无基类</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">存放位置</label>
                <div class="layui-input-block">
                    <select>
                        <option value="Admin.NET.Application">Admin.NET.Application</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="submit" class="layui-btn" lay-submit lay-filter="createEntity">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>

    <div id="divWin_2" class="layui-padding-3" style="display:none">
        <form class="layui-form" action="" lay-filter="val-filter">
            <div class="layui-form-item">
                <label class="layui-form-label">名称</label>
                <div class="layui-input-block">
                    <input type="hidden" name="configId">
                    <input type="hidden" name="tableName">
                    <input type="hidden" name="oldColumnName">
                    <input type="text" name="columnName" lay-verify="required" placeholder="请输入列名称" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">描述</label>
                <div class="layui-input-block">
                    <input type="text" name="description" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="submit" class="layui-btn" lay-submit lay-filter="updateColumn">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>
}

@section scripts {
    <script type="text/javascript">
        var app = { configId: '', curNode: null, tablename: '' };
        layui.use(['http', 'dtree', 'toast', 'tools'], function () {
            var $ = layui.jquery,
                laytpl = layui.laytpl, dtree = layui.dtree, table = layui.table, dropdown = layui.dropdown, form = layui.form,
                http = layui.http, toast = layui.toast, tools = layui.tools;
            //加载
            app.load = function () {
                http.get('/api/sysDatabase/list').then((res) => {
                    let arrdb = [];
                    $.each(res.result, function (i, val) {
                        arrdb.push({ id: val, title: val, parentId: '', last: false })
                    });
                    app.dttree = dtree.render({
                        elem: "#demoTree",
                        initLevel: "1",
                        ficon: "-1",
                        data: arrdb
                    });
                    //树节点点击事件
                    dtree.on("node(demoTree)", function (obj) {
                        if (!obj.param.leaf) {
                            app.configId = obj.param.nodeId;
                            app.curNode = obj.dom;
                            app.loadTables();
                            $('#btnAddColumn').addClass('layui-hide');
                            $('#btnAddTable').removeClass('layui-hide');
                        }
                        else {
                            app.tablename = obj.param.nodeId;
                            app.loadColumns();
                            $('#btnAddColumn').removeClass('layui-hide');                           
                        }
                    });

                });
            }
            //加载所有表
            app.loadTables = function () {
                $('#key').html('【所有表】');
                http.get('/api/sysDatabase/tableList/' + app.configId).then((res) => {
                    let arrtable = [];
                    $.each(res.result, function (i, item) {
                        arrtable.push({ id: item.name, title: item.name, parentId: app.configId })
                    });
                    app.dttree.partialRefreshAdd(app.curNode, arrtable);
                    //
                    table.render({
                        even: true,
                        page: true, // 是否显示分页
                        height: 'full-80',
                        limits: [20, 50, 100],
                        limit: 20, // 每页默认显示的数量
                        elem: '#lsttable',
                        cols: [[ //标题栏
                            { field: 'LAY_NUM', title: '序号', width: 60 },
                            { field: 'name', title: '表名', width: 220, sort: true },
                            { field: 'description', title: '描述' },
                            { field: 'dbObjectType', title: '类型', width: 80, templet: function (d) { return d.dbObjectType == 0 ? '表' : '试图'; } },
                            { fixed: 'right', title: '操作', width: 200, toolbar: '#bar' }
                        ]],
                        data: res.result
                    });
                    //
                    table.on('tool(lsttable)', function (obj) {
                        var data = obj.data;
                        switch (obj.event) {
                            case 'edit':
                                app.editTable(data);
                                break;
                            case 'del':
                                app.deleteTable(data);
                                break;
                            case 'more':
                                app.showMore(this, data);
                                break;
                            case 'edit_1':
                                app.editColumn(data);
                                break;
                            case 'del_1':
                                app.deleteColumn(data);
                                break;
                        };
                    });
                });
            }
            //加载指定表的列
            app.loadColumns = function () {
                $('#key').html('【' + app.tablename + '】表');
                http.get('/api/sysDatabase/columnList/' + app.tablename + '/' + app.configId).then((res) => {
                    table.render({
                        even: true,
                        page: true, // 是否显示分页
                        height: 'full-80',
                        limits: [20, 50, 100],
                        limit: 20, // 每页默认显示的数量
                        elem: '#lsttable',
                        cols: [[ //标题栏
                            { field: 'LAY_NUM', title: '序号', width: 60 },
                            { field: 'dbColumnName', title: '列名', width: 220, sort: true },
                            { field: 'dataType', title: '类型', width: 120 },
                            { field: 'isPrimarykey', title: '主键', width: 60, templet: function (d) { return d.isPrimarykey ? '<span class="layui-badge layui-bg-blue">是</span>' : '<span class="layui-badge layui-bg-black">否</span>'; } },
                            { field: 'isIdentity', title: '自增', width: 60, templet: function (d) { return d.isIdentity ? '<span class="layui-badge">是</span>' : '<span class="layui-badge layui-bg-black">否</span>'; } },
                            { field: 'isNullable', title: '可空', width: 60, templet: function (d) { return d.isNullable ? '<span class="layui-badge">是</span>' : '<span class="layui-badge layui-bg-black">否</span>'; } },
                            { field: 'length', title: '长度', width: 80, align: 'right' },
                            { field: 'decimalDigits', title: '精度', width: 80, align: 'right' },
                            { field: 'defaultValue', title: '默认值' },
                            { field: 'columnDescription', title: '描述' },
                            { fixed: 'right', title: '操作', width: 150, toolbar: '#bar_1' }
                        ]],
                        data: res.result
                    });
                })
            }
            //显示更多操作
            app.showMore = function (obj, data) {
                dropdown.render({
                    elem: obj, // 触发事件的 DOM 对象
                    show: true, // 外部事件触发即显示
                    data: [{
                        title: '生成实体',
                        id: 'createEntity'
                    }, {
                        title: '生成种子数据',
                        id: 'createSeedData'
                    }],
                    click: function (menudata) {
                        switch (menudata.id) {
                            case 'createEntity':
                                app.createEntity(data);
                                break;
                            case 'createSeedData':
                                app.createSeedData(data);
                                break;
                        };
                    }
                })
            }
            //编辑表
            app.editTable = function (data) {
                form.val('val-filter', {
                    configId: app.configId,
                    description: data.description,
                    oldTableName: data.name,
                    tableName: data.name
                });
                var index = layer.open({
                    type: 1,
                    area: ['500px', '300px'],
                    title: '编辑表',
                    shade: 0.6, // 遮罩透明度
                    content: $('#divWin')
                });
                //
                form.on('submit(saveTable)', function (data) {
                    var field = data.field;
                    http.post('/api/sysDatabase/updateTable', field).then((res) => {
                        if (res.code == 200) {
                            app.loadTables();
                            layer.close(index);
                            toast.success({ message: '保存成功！' });
                        }
                        else {
                            layer.alert('保存失败，错误信息:' + res.message, { icon: 2 });
                        }
                    });
                    return false; // 阻止默认 form 跳转
                });
            }
            //编辑列
            app.editColumn = function (data) {
                form.val('val-filter', {
                    configId: app.configId,
                    tableName: app.tablename,
                    description: data.description,
                    columnName: data.dbColumnName,
                    oldColumnName: data.dbColumnName
                });
                var index = layer.open({
                    type: 1,
                    area: ['500px', '300px'],
                    title: '编辑列',
                    shade: 0.6, // 遮罩透明度
                    content: $('#divWin_2')
                });
                //
                form.on('submit(updateColumn)', function (data) {
                    var field = data.field;
                    http.post('/api/sysDatabase/updateColumn', field).then((res) => {
                        if (res.code == 200) {
                            app.loadColumns();
                            layer.close(index);
                            toast.success({ message: '保存成功！' });
                        }
                        else {
                            layer.alert('保存失败，错误信息:' + res.message, { icon: 2 });
                        }
                    });
                    return false; // 阻止默认 form 跳转
                });
            }
            //添加表
            app.addTable = function () {
                tools.open({
                    area: ['80%', '100%'],
                    content: './tableAdd',
                    title: '新建表',
                    success: function (layero, index, that) {
                        var iframeWin = window[layero.find('iframe')[0]['name']];
                        iframeWin.app.data = {
                            configId: app.configId
                        };
                    },
                    yes: function (index, layero) {
                        var iframeWin = window[layero.find('iframe')[0]['name']];
                        iframeWin.app.save();
                    }
                });
            }
            //添加列
            app.addColumn = function () {
                tools.open({
                    area: ['700px', '100%'],
                    content: './columnAdd',
                    title: '添加列',
                    success: function (layero, index, that) {
                        var iframeWin = window[layero.find('iframe')[0]['name']];
                        iframeWin.app.data = {
                            configId: app.configId,
                            tableName: app.tablename
                        };
                    },
                    yes: function (index, layero) {
                        var iframeWin = window[layero.find('iframe')[0]['name']];
                        iframeWin.app.save();
                    }
                });
            }
            //生成实体
            app.createEntity = function (data) {
                form.val('val-filter_1', {
                    configId: app.configId,
                    tableName: data.name,
                    entityName: data.name,
                    baseClassName: 'EntityBase',
                    position: 'Admin.NET.Application'
                });
                var index = layer.open({
                    type: 1,
                    area: ['600px', '360px'],
                    title: '生成实体',
                    shade: 0.6, // 遮罩透明度
                    content: $('#divWin_1')
                });

                form.on('submit(createEntity)', function (data) {
                    var field = data.field;
                    http.post('/api/sysDatabase/createEntity', field).then((res) => {
                        if (res.code == 200) {
                            layer.close(index);
                            toast.success({ message: '生成成功！' });
                        }
                        else {
                            layer.alert('生成失败，错误信息:' + res.message, { icon: 2 });
                        }
                    });
                    return false; // 阻止默认 form 跳转
                });
            }
            //生成种子数据
            app.createSeedData = function (data) {
                var postData = {
                    configId: app.configId,
                    tableName: data.name,
                    suffix: '',
                    position: 'Admin.NET.Application'
                };
                http.post('/api/sysDatabase/createSeedData', postData).then((res) => {
                    if (res.code == 200) {
                        toast.success({ message: '生成成功！' });
                    }
                    else {
                        layer.alert('生成失败，错误信息:' + res.message, { icon: 2 });
                    }
                });
            }
            //删除表
            app.deleteTable = function (data) {
                var index = layer.confirm('您确定要删除当前表吗？', function () {
                    var url = '/api/sysDatabase/deleteTable';
                    http.post(url, {
                        configId: app.configId, tableName: data.name
                    }).then((res) => {
                        layer.close(index);
                        app.loadTables();
                    });
                })
            }
            //删除列
            app.deleteColumn = function (data) {
                var index = layer.confirm('您确定要删除当前列吗？', function () {
                    var url = '/api/sysDatabase/deleteColumn';
                    http.post(url, {
                        configId: app.configId, tableName: app.tablename, dbColumnName: data.dbColumnName
                    }).then((res) => {
                        layer.close(index);
                        app.loadColumns();
                    });
                })
            }
            //
            app.init = function () {
                app.load();
                $('#btnAddTable').on('click', app.addTable);
                $('#btnAddColumn').on('click', app.addColumn);
                $('#btnReload').on('click', app.loadTables);
            }();
        });
    </script>
}